package com.glsc.ngateway.platform.controller.dev;

import com.glsc.ngateway.common.api.flowable.dto.*;
import com.glsc.ngateway.common.api.flowable.feign.IFeignFlowableService;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.platform.domain.DevManageDto;
import com.glsc.ngateway.platform.dto.FlowParamDevManageSearchDto;
import com.glsc.ngateway.platform.dto.GiteeDataBaseDto;
import com.glsc.ngateway.platform.dto.ResponseSituationDevManageDto;
import com.glsc.ngateway.platform.service.dev.DevManageService;
import com.glsc.ngateway.platform.service.FlowCommonService;
import com.glsc.ngateway.platform.service.gitee.GiteeNewService;
import com.glsc.ngateway.platform.utils.RequestTool;
import com.glsc.ngateway.platform.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping(value = "/devManage")
@Api(value = "研发需求管理流程接口", tags = {"研发需求管理流程接口"})
public class FlowDevManageController {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    private static int default_page_number = 1;
    private static int default_page_size = 10;


    @Resource
    private IFeignFlowableService feignDemandService;

    @Resource
    private DevManageService devManageService;

    @Resource
    private GiteeNewService giteeNewService;

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private RequestTool requestTool;

    @Resource
    private FlowCommonService flowCommonService;

    @Value("${demand.downloadUrl}")
    String downloadUrl;

    /**
     * 流程发起
     *
     * @param devManageDto 流程创建表单数据
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/createFlow")
    public PlatformResponse<FlowDoTaskRespDto> createFlow(@RequestBody DevManageDto devManageDto) {
        PlatformResponse<FlowDoTaskRespDto> ret = null;
        try {
            String operatorStart = requestTool.getAccountFromRequest();
            FlowDoTaskRespDto respDto = devManageService.createFlow(devManageDto, operatorStart);
            ret = PlatformResponse.successData(respDto);
        } catch (Exception e) {
            logger.error("createFlow！", e);
            ret = PlatformResponse.failedMsg("操作失败", e.getMessage());
        }

        return ret;
    }


    /**
     * 保存节点数据，但是不提交任务
     */
    @PostMapping("/saveFormData")
    @ApiOperation(value = "保存节点数据", notes = "保存节点数据")
    public PlatformResponse<FlowDoTaskRespDto> saveFormData(@RequestBody DevManageDto devManageDto) {
        logger.info("保存节点数据，{}", devManageDto);

        String operatorStart = requestTool.getAccountFromRequest();

        FlowDoTaskRespDto respDto = devManageService.saveFormData(devManageDto, operatorStart,true);
        return PlatformResponse.successData(respDto);
    }


    /**
     * 审核通过
     */
    @PostMapping("/taskAuditPass")
    @ApiOperation(value = "审核通过", notes = "流程审核处理通过")
    public PlatformResponse<FlowDoTaskRespDto> taskAuditPass(@RequestBody DevManageDto devManageDto) {
        logger.info("审核任务，" + devManageDto);

        String operatorStart = requestTool.getAccountFromRequest();
        FlowDoTaskRespDto respDto = devManageService.taskAuditPass(devManageDto, operatorStart);
        return PlatformResponse.successData(respDto);
    }

    /**
     * 审核驳回
     */
    @PostMapping("/taskAuditReject")
    @ApiOperation(value = "审核驳回，返回上一个节点", notes = "流程审核驳回处理")
    public PlatformResponse<FlowDoTaskRespDto> taskAuditReject(@RequestBody DevManageDto devManageDto) {
        logger.info("驳回，返回上一个节点，" + devManageDto);

        String operatorStart = requestTool.getAccountFromRequest();
        FlowDoTaskRespDto respDto = devManageService.taskAuditReject(devManageDto, operatorStart);

        return PlatformResponse.successData(respDto);
    }

    @RequestMapping("/getDataBaseList")
    @ApiOperation(value = "获取git仓库列表", notes = "获取git仓库列表")
    public PlatformResponse<List<GiteeDataBaseDto>> getDataBaseList() throws UnsupportedEncodingException {

//        String operatorStart = requestTool.getAccountFromRequest();
        List<GiteeDataBaseDto> respDto = giteeNewService.getDataBaseList();

        return PlatformResponse.successData(respDto);
    }

    @RequestMapping("/getProgramDataBaseList")
    @ApiOperation(value = "获取项目的git仓库列表", notes = "获取项目的git仓库列表")
    public PlatformResponse<List<GiteeDataBaseDto>> getProgramDataBaseList(@RequestParam(value = "systemName", required = true) String systemName){

        List<GiteeDataBaseDto> respDto = null;
        try {
            respDto = giteeNewService.getProgramDataBaseList(systemName);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return PlatformResponse.failedMsg("获取项目仓库失败，检查项目名称是否对应，部门领导是否有项目和仓库权限");
        }

        return PlatformResponse.successData(respDto);
    }

    @RequestMapping("/getDataBaseBranchList")
    @ApiOperation(value = "获取项目的git仓库列表", notes = "获取项目的git仓库分支列表")
    public PlatformResponse<List<GiteeDataBaseDto>> getDataBaseBranchList(@RequestParam(value = "dataBaseId", required = true) String dataBaseId){

        List<GiteeDataBaseDto> respDto = null;
        try {
            respDto = giteeNewService.getDataBaseBranchList(dataBaseId);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return PlatformResponse.failedMsg("获取项目的git仓库分支列表，检查项目名称是否对应，部门领导是否有项目和仓库权限");
        }

        return PlatformResponse.successData(respDto);
    }

    /**
     * 根据流程实例ID或者任务ID检索流程
     *
     * @param devManageDto processId 流程ID
     * @param devManageDto taskId 任务ID
     */
    @PostMapping("/findByProcessIdOrTaskId")
    @ApiOperation(value = "根据流程实例ID或者任务ID检索流程", notes = "根据流程实例ID或者任务ID检索流程状态、备注等，如提供流程实例ID则认为只读方式获取数据")
    public PlatformResponse<DevManageDto> findByProcessIdOrTaskId(@RequestBody DevManageDto devManageDto) {
        logger.info("查询流程内容，" + devManageDto);
        DevManageDto respDto = devManageService.getWorkFlowFormByTaskId(devManageDto);
        return PlatformResponse.successData(respDto);
    }


    @ApiOperation(value = "流程分页查询-调试", notes = "流程分页查询")
    @RequestMapping("/findProcessPage")
    public PlatformResponse<Page<ResponseSituationDevManageDto>> getProcessSituationPage(
            @ApiParam(value = "流程查询参数") @RequestBody(required = true) FlowParamDevManageSearchDto paramSearchDto) {
        logger.info("流程已办列表分页查询");
        paramSearchDto.setSystemCode(Strings.isNotBlank(paramSearchDto.getSystemCode()) ? paramSearchDto.getSystemCode() : null);
        String operatorStart = requestTool.getAccountFromRequest();
        Page<ResponseSituationDevManageDto> page = devManageService.getProcessSituationPage(paramSearchDto.getPageNo(), paramSearchDto.getPageSize(), paramSearchDto, operatorStart);
        return PlatformResponse.successData(page);
    }

    @GetMapping("/download")
    @ApiOperation(value = "下载文件模板文件")
    public void download(HttpServletResponse response) throws UnsupportedEncodingException {
        //强制下载不打开
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        //使用URLEncoder来防止文件名乱码或者读取错误
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("需求附件模板.zip", "UTF-8"));
        try (InputStream input = this.getClass().getResourceAsStream("/templates/dev_manage_templates.zip")) {
            OutputStream output = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = input.read(buffer))!=  -1) {
                output.write(buffer,  0, bytesRead);
            }
            output.flush();
        } catch (IOException e) {
            logger.error("Error", e);
        }
    }

//    @ApiOperation(value = "流程分页查询-调试", notes = "流程分页查询")
//    @RequestMapping("/export")
//    public byte[] export(@ApiParam(value = "流程查询参数") @RequestBody FlowParamSearchDto paramSearchDto
//            , HttpServletResponse response) throws IOException {
//        response.setHeader("Content-Disposition", "attachment;" + "filename=" + URLEncoder.encode(ReportFileConfigEnum.EVENT_FLOW.getFileName(), "UTF-8"));
//        String operatorStart = requestTool.getAccountFromRequest();
//        return devManageService.export(paramSearchDto, operatorStart);
//    }

    /**
     * 事件统计
     */
//    @PostMapping("/eventStatistics")
//    @ApiOperation(value = "事件统计", notes = "事件统计")
//    public PlatformResponse<Map> eventStatistics(@RequestBody(required = false) EventStatisticParamDto param) {
//        String operatorStart = requestTool.getAccountFromRequest();
//        Map<String, List<EventStatisticDto>> respDto = devManageService.eventStatistics(param, operatorStart);
//        return PlatformResponse.successData(respDto);
//    }
}
